<template>
  <div class="container py-5">
    <div class="row">
      <div class="col-12">
        <h2 class="text-center mb-4">积分充值</h2>
        <div class="card shadow-sm mb-4">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <h5 class="mb-0">当前积分余额:</h5>
              <span class="fs-4 fw-bold text-primary">{{ userPoints }}</span>
            </div>
          </div>
        </div>
        <div class="card shadow-sm">
          <div class="card-body">
            <div class="row g-4 mb-4">
              <div v-for="(product, index) in products" :key="index" class="col-md-3 col-6">
                <div 
                  class="card h-100 product-card" 
                  :class="{ 'selected': selectedProduct === index }"
                  @click="selectProduct(index)"
                >
                  <div class="card-body text-center">
                    <h5 class="card-title">{{ product.points }}积分</h5>
                    <p class="price mb-0">¥{{ product.price }}</p>
                    <div class="badge bg-success mt-2" v-if="product.isBest">最佳选择</div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="row mt-4">
              <div class="col-12">
                <div class="d-grid">
                  <button 
                    class="btn btn-primary btn-lg" 
                    :disabled="selectedProduct === null || isLoading"
                    @click="handleCreateOrder"
                  >
                    <span v-if="isLoading" class="spinner-border spinner-border-sm me-2" role="status"></span>
                    {{ isLoading ? '处理中...' : '立即充值' }}
                  </button>
                </div>
              </div>
            </div>
            
            <div class="alert alert-danger mt-3" v-if="errorMessage">
              {{ errorMessage }}
            </div>
            
            <div class="row mt-4">
              <div class="col-12">
                <div class="alert alert-info">
                  <h5>积分说明：</h5>
                  <p class="mb-0">积分可用于解锁高级测量功能，获取详细分析报告等服务。充值越多，单位积分越划算。</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'pinia'
import { useUserStore } from '../store/userStore'
import { orderService } from '../api'

export default {
  name: 'Recharge',
  data() {
    return {
      products: [
        { price: 5, points: 20, isBest: false },
        { price: 10, points: 40, isBest: false },
        { price: 20, points: 80, isBest: true },
        { price: 25, points: 100, isBest: false }
      ],
      selectedProduct: null,
      isLoading: false,
      errorMessage: ''
    }
  },
  computed: {
    ...mapState(useUserStore, ['userPoints'])
  },
  methods: {
    selectProduct(index) {
      this.selectedProduct = index;
      this.errorMessage = '';
    },
    async handleCreateOrder() {
      if (this.selectedProduct === null) return;
      
      const product = this.products[this.selectedProduct];
      this.isLoading = true;
      this.errorMessage = '';
      
      try {
        // 创建订单
        const result = await orderService.createOrder({
          order_amount: product.price.toString()
        });
        
        if (result.success) {
          // 订单创建成功，跳转到支付页面
          this.$router.push({
            path: '/payment',
            query: { 
              order_id: result.data.id,
              order_trade_no: result.data.order_trade_no,
              amount: result.data.order_amount
            }
          });
        } else {
          this.errorMessage = result.message || '创建订单失败，请稍后重试';
        }
      } catch (error) {
        console.error('创建订单错误:', error);
        this.errorMessage = '系统错误，请稍后重试';
      } finally {
        this.isLoading = false;
      }
    },
    // 保留旧的充值方法，以备后续需要
    async handleRecharge() {
      if (this.selectedProduct === null) return;
      
      const product = this.products[this.selectedProduct];
      this.isLoading = true;
      this.errorMessage = '';
      
      try {
        const userStore = useUserStore();
        const result = await userStore.rechargePoints({
          amount: product.price,
          points: product.points
        });
        
        if (result.success) {
          // 显示成功消息
          this.$router.push({
            path: '/profile',
            query: { rechargeSuccess: 'true', amount: product.points }
          });
        } else {
          this.errorMessage = result.error || '充值失败，请稍后重试';
        }
      } catch (error) {
        console.error('充值处理错误:', error);
        this.errorMessage = '系统错误，请稍后重试';
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.product-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.product-card.selected {
  border-color: #0d6efd;
  background-color: rgba(13, 110, 253, 0.05);
}

.price {
  font-size: 1.5rem;
  font-weight: bold;
  color: #dc3545;
}

.badge {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style> 